<template>
  <z-modal @ok="submit" @open="assignValue">
    <z-form
      class="w-72 md:w-2xl lg:w-3xl"
      ref="form"
      :model="values"
      :rules="rules"
      autocomplete="off"
      @success="onSuccess"
    >
      <z-form-item name="title" label="标题" outline>
        <z-input name="title" v-model="values.title" />
      </z-form-item>
      <z-form-item name="sketch" label="简述" outline>
        <z-textarea name="sketch" v-model="values.sketch" rows="5"></z-textarea>
      </z-form-item>
      <z-form-item name="priority" label="优先级" outline>
        <div class="flex items-center space-x-4 p-2">
          <z-input-radio
            v-for="(val, key) in TodoPriority"
            name="priority"
            :label="val"
            :value="key"
            :key="key"
            v-model="values.priority"
          />
        </div>
      </z-form-item>
    </z-form>
  </z-modal>
</template>
<script lang="ts" setup>
import { ref, reactive } from "vue";

import { Rules, Values } from "@/pkg/validate";
import ZForm from "@/components/forms/ZForm.vue";
import ZInputRadio from "@/components/forms/ZInputRadio.vue";

import { useTodosStore } from "@/stores/todos";

const todosStore = useTodosStore();

const TodoPriority = {
  Normal: "一般",
  Important: "重要",
  Crucial: "至关重要",
};
const emit = defineEmits(["success"]),
  props = defineProps<{ initValues: any; update?: boolean }>();

const values = reactive<{
    title: string;
    sketch: string;
    priority: string;
  }>(Object.assign({}, props.initValues)),
  rules: Rules = {
    title: [
      {
        required: true,
      },
      {
        minLength: 3,
        maxLength: 100,
        message: "标题必须在3到100个字符之间",
      },
    ],
    sketch: [
      {
        required: true,
        message: "简述不能为空",
      },
      {
        minLength: 3,
        maxLength: 255,
        message: "简述必须在3到255个字符之间",
      },
    ],
  },
  form = ref<InstanceType<typeof ZForm>>();
const onSuccess = async (todo: Values) => {
    // ajax 发送 FormData 数据
    const data = props.update
      ? await todosStore.editTodo(todo)
      : await todosStore.addTodo(todo);
    // 设置表单错误显示
    if (data?.errors) form.value?.setErrors(data.errors);
    if (data?.success) emit("success", data.object);
  },
  submit = () => {
    form.value?.onSubmit();
  },
  assignValue = () => {
    Object.assign(values, props.initValues);
  };
defineExpose({
  submit,
});
</script>
